package be.dch.objectprops.impl;

import org.apache.log4j.Logger;

public class ObjectUtil {

    private static final Logger LOG = Logger.getLogger(ObjectUtil.class);

    public static Object newInstance(final String className) {
	try {
	    return ObjectUtil.newInstance(Class.forName(className));
	} catch (final ClassNotFoundException e) {
	    ObjectUtil.LOG.error(e);
	}
	return null;
    }

    public static Object newInstance(final Class<?> clazz) {

	final Object object = null;
	if (clazz.isInterface()) {
	    ObjectUtil.LOG.error(clazz.getSimpleName() + " is an interface");
	} else if (clazz.isPrimitive()) {
	    ObjectUtil.LOG.error(clazz.getSimpleName() + " is primitive");
	} else {
	    ObjectUtil.LOG.debug("Creating instance of clazz: " + clazz);
	    try {
		return clazz.newInstance();
	    } catch (final InstantiationException e) {
		ObjectUtil.LOG.debug("Could not find default constructor for " + clazz + " using ObjectStreamClassInstantiator.");
		try {
		    final ObjectStreamClassInstantiator init = new ObjectStreamClassInstantiator(clazz);
		    return init.newInstance();
		} catch (final Exception ex) {
		    ObjectUtil.LOG.error(ex);
		}
	    } catch (final IllegalAccessException e) {
		ObjectUtil.LOG.error(e);
	    }
	}
	return object;
    }
}
